package top.chukongxiang.monitorservice.config.listener;

import cn.hutool.core.thread.ThreadUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
import top.chukongxiang.monitorservice.config.ApplicationState;
import top.chukongxiang.monitorservice.config.ApplicationStatusContextHolder;
import top.chukongxiang.monitorservice.config.SdkServerContextHolder;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2023/10/24 11:03
 */
@Component
public class ApplicationStoppedListener implements ApplicationListener<ContextClosedEvent> {
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        ApplicationStatusContextHolder.setState(ApplicationState.STOPPING);
        ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event.getApplicationContext();
        ThreadUtil.execute(() -> {
            while (applicationContext.isActive()) {}
            ApplicationStatusContextHolder.setState(ApplicationState.STOPPED);
            SdkServerContextHolder.clear();
        });
    }
}
